package nc.bs.common.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author duanyp1
 * @date 2024/3/18 16:18
 */
public class ArrayUtil {


    public static <T> boolean contain(T[] origin, Object target) {
        return test(origin, src -> src.equals(target));
    }

    public static <T> boolean containPrefix(T[] origin, String target) {
        if (target == null) {
            return false;
        }
        return test(origin, src -> target.equals(src) || (target.startsWith((String) src)));
    }

    private static <T> boolean test(T[] origin, Predicate<T> predicate) {
        if (origin == null) {
            return false;
        }
        for (T t : origin) {
            if (predicate.test(t)) {
                return true;
            }
        }
        return false;
    }


    public static <T> T[] merge(T[] a, T[] b) {
        Set<T> uniqueElements = new HashSet<>();
        Set<T> setA = new HashSet<>(Arrays.asList(a));
        Set<T> setB = new HashSet<>(Arrays.asList(b));
        @SuppressWarnings("unchecked")
        T[] mergedArray = (T[]) Stream.of(setA, setB)
                .flatMap(Set::stream)
                .distinct().toArray();
        return mergedArray;
    }

}
